import React, {createContext, useContext, useReducer} from 'react';
import * as constants from '../constants'

export const AuthContext = createContext()

export function useAuth() {
    return useContext(AuthContext)
}


const AuthReducer = (state, action) => {
    switch (action.type) {
        case constants.LOGIN_SUCCESS:
            localStorage.setItem('access', action.payload.access)
            localStorage.setItem('refresh', action.payload.refresh)
            return true
        case constants.LOGOUT_SUCCESS:
            localStorage.removeItem('access')
            localStorage.removeItem('refresh')
            return false
        case constants.ACCESS_TOKEN_EXPIRED:   // 过期后删除access token
            localStorage.removeItem('access')
            return false
        case constants.GET_USER_SUCCESS:
            return true
        default:
            return false
    }
}

export default function AuthContextProvider(props) {
    const [isAuthenticated, dispatch] = useReducer(AuthReducer, [], () => {
        const accessToken = localStorage.getItem('access')
        return !!accessToken
    })

    return (
        <AuthContext.Provider value={{isAuthenticated, dispatch}}>
            {props.children}
        </AuthContext.Provider>
    );
};























